
/**
 * Controller of the webapp
 */
var MikuClip = new (function() {

	var $this = this;
	var init = false;
	var verified = false;
	this.options = {};
	
	/**
	 * URLs used for AJAX
	 */
	this.URL = {
		WEBSERVICE_TAGS: 			'webservices/tags/tags.php',
		WEBSERVICE_VIDEOS_TAGS: 	'webservices/videos/tag.php',
		WEBSERVICE_VIDEOS_RANK: 	'webservices/videos/top20.php',
		WEBSERVICE_VIDEOS_SEARCH: 	'webservices/videos/words.php',
		WEBSERVICE_LOGIN: 			'webservices/login/check.php',
		WEBSERVICE_VIDEOS_NEWEST:	'webservices/videos/newest.php'
	}
	
	/**
	 * Check if there are a login, and if not forced the connection to Mikubook.com
	 */
	function verifMikuClipLogin() {
		
		if (!verified && (!$this.options.login || !$this.options.password)) {
			window.setTimeout(function() { DialogConnectMikubook.show(); }, 250);
			verified = true;
		}
	}
	
	/**
	 * Initialization
	 * Load settings and set default lang
	 */
	this.init = function() {
		if (!init) {
			$this.loadOptions();
			WebappI18n.setDefaultLang($this.options.lang);
			init = true;
		}
	};
	
	/**
	 * Show a dialog
	 */
	this.showDialog = function(page) {
		$.mobile.changePage(page, {transition: 'pop', role: 'dialog'});
	}
	
	/**
	 * Load the application settings
	 */
	this.loadOptions = function() {
		var options = {
			login: '',
			password: '',
			youtubeQuality: 'default',
			lang: 'en'
		};
		if (typeof(localStorage['mikuclip_options']) != "undefined") {
			options = JSON.parse(localStorage['mikuclip_options']);
		}
		$this.options = options;
		return options;
	};
	
	/**
	 * Change application settings
	 */
	this.setOptions = function(options) {
		var newlang = false;
		if (options.lang && options.lang != $this.options.lang) {
			newlang = true;
		}
		for (var i in options) {
			$this.options[i] = options[i];
		}
		$this.saveOptions();
		$this.loadOptions();
		if (newlang) {
			WebappI18n.setDefaultLang($this.options.lang);
			WebappI18n.refreshPage();
		}
	};
	
	/**
	 * Save the settings
	 */
	this.saveOptions = function() {
		localStorage['mikuclip_options'] = JSON.stringify($this.options);
	}
	
	$(document).on("pageinit", this.init);
	$(document).on("pageshow", verifMikuClipLogin);
	$(document).ready(this.init);
})();